package com.common.util.antihijack;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.Application;
import android.content.ComponentName;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.WindowManager;

import com.common.util.BuildConfig;
import com.common.util.utils.ApplicationManager;

import java.util.List;

/**
 * @文件名称：AppLifecycleCallback.java
 * @文件作者：ljb
 * @文件描述：
 * @版本： 1.0.0
 * @创建时间：2017-12-19 17:40
 * @修改历史：2017-12-19 17:40
 */

class AppLifecycleCallback implements Application.ActivityLifecycleCallbacks {

    private static final int ON_FRONT_TO_BACK = 100;
    private static final int ON_BACK_TO_FRONT = 101;
    private boolean isForground = true;
    private Handler handler;
    private ActivityManager am;
    private String packageName;

    public AppLifecycleCallback() {
        Context context = ApplicationManager.getInstance().getContext();
        am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        packageName = context.getPackageName();
        handler = new Handler(Looper.getMainLooper()) {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case ON_BACK_TO_FRONT:
                        AppEventManager.getInstance().notifyAppStateChange(true);
                        break;
                    case ON_FRONT_TO_BACK:
                        AppEventManager.getInstance().notifyAppStateChange(false);
                        break;
                    default:
                        break;
                }
            }
        };
    }

    @Override
    public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
        if (BuildConfig.DEBUG) {
            // 禁止截屏
            activity.getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE);
        }

    }

    @Override
    public void onActivityStarted(Activity activity) {
        if (!isForground) {
            isForground = true;
            handler.sendEmptyMessage(ON_BACK_TO_FRONT);
        }
    }
    @Override
    public void onActivityResumed(Activity activity) {

    }

    @Override
    public void onActivityPaused(Activity activity) {

    }

    @Override
    public void onActivityStopped(Activity activity) {
        if (!isInForground()) {
            isForground = false;
            handler.sendEmptyMessage(ON_FRONT_TO_BACK);
        }
    }

    @Override
    public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

    }

    @Override
    public void onActivityDestroyed(Activity activity) {

    }

    /**
     * 判断应用在前台可见进程
     * @return
     */
    public boolean isInForground() {
        // 5.0之前版本
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            return isInForgroundCompat();
        }


        // 5.0以上设备使用下面的方法
        List<ActivityManager.RunningAppProcessInfo> appProcessInfos = am.getRunningAppProcesses();
        if (appProcessInfos == null || appProcessInfos.size() <= 0) {
            return false;
        }
        for (ActivityManager.RunningAppProcessInfo appProcess : appProcessInfos) {
            if (appProcess.processName.equals(packageName) && appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                return true;
            }
        }

        return false;
    }

    public boolean isInForgroundCompat() {
        List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(1);
        if (tasks != null && !tasks.isEmpty()) {
            ComponentName topActivity = tasks.get(0).topActivity;
            if (topActivity.getPackageName().equals(packageName)) {
                return true;
            }
        }

        return false;
    }
}
